<template>
<div class="choose-userlist">
    <el-button :disabled="disabled" style="margin-bottom:5px;" v-if="config.isNotUnique || !saveList.length" type="primary" @click="dialogTableVisible = true">选择用户</el-button>
    <div class="tag-list">
        <el-tag :key="tag.user_id" v-for="(tag,index) in saveList" :closable="config.closable" :disable-transitions="false" @close="handleClose(tag,index)">
            {{tag.nickName || tag.user_name }}
        </el-tag>
    </div>
    <el-dialog width="55%" custom-class="wlm-form-dialog dialog-table" :append-to-body="true" :visible.sync="dialogTableVisible">
        <div class="wlm-dialog-fixheader">
            <span v-if="isUser" class="wlm-dialog-inlenr">用户列表</span>
            <span v-if="isDistributor" class="wlm-dialog-inlenr">分销用户列表</span>
        </div>
        <el-scrollbar>
            <div class="wlm-table-header" style="margin-bottom:-30px;margin-top:20px;">
                <el-form :model="tableFormatData.userTable.files" size="small" label-width="60px" class="retail-form" label-position="right">
                    <el-form-item label="" class="filter" label-width="10px">
                        <el-form-item label="用户：" class="search">
                            <el-input v-if="isUser" v-model="tableFormatData.userTable.files.keyword" placeholder="请输入昵称或手机号" style="width:160px;"></el-input>
                            <el-input v-if="isDistributor" v-model="tableFormatData.userTable.files.real_name" placeholder="请输入姓名" style="width:160px;"></el-input>
                            <el-button style="margin-left:10px;" type="primary" @click="filesSerch">搜索</el-button>
                            <!-- <el-button type="text" @click="filesEmpty">刷新</el-button> -->
                        </el-form-item>
                    </el-form-item>
                </el-form>
            </div>
            <div class="wlm-table-content">
                <div class="wlm-dialog-main">
                    <el-table ref="userTable" :data="tableFormatData.userTable.tableData" @selection-change="handleSelectionChange">
                        <el-table-column v-if="!config.isNotUnique" label="" width="55">
                            <template slot-scope="scope">
                                <el-checkbox v-model="scope.row.checked" @change="handleSelectionChange(scope)"></el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="config.isNotUnique" label="" type="selection" width="55">
                        </el-table-column>
                        <el-table-column label="用户" v-if="!isAdmin">
                            <template slot-scope="scope">
                                <div class="flex-row flex-align-c">
                                    <div class="wlm-table-logos">
                                        <img class="logo" :src="scope.row.avatarUrl || $store.getters.usersAvatar" style="margin-right:10px;">
                                    </div>
                                    <div class="text-left">
                                        <el-popover trigger="hover" placement="top">
                                            <p>{{scope.row.nickName || '-'}}</p>
                                            <div slot="reference" class="wlm-table-wrapper" style="width:100px;">
                                                <p>{{scope.row.nickName || '-'}}</p>
                                            </div>
                                        </el-popover>
                                        <p>{{`ID：${scope.row.user_id}` || '-'}}</p>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <template v-if="isUser">
                            <template v-if="!isAdmin">
                                <el-table-column label="姓名">
                                    <template slot-scope="scope">
                                        {{scope.row.realname || '-'}}
                                    </template>
                                </el-table-column>
                                <el-table-column label="渠道来源">
                                    <template slot-scope="scope">
                                        <p>{{sourceType[`${scope.row.source}`]}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column label="手机号">
                                    <template slot-scope="scope">
                                        {{scope.row.mobile || '-'}}
                                    </template>
                                </el-table-column>
                                <el-table-column label="注册时间">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.create_time }}</span>
                                    </template>
                                </el-table-column>
                            </template>
                            <template v-if="isAdmin">
                                <el-table-column label="登录账号">
                                    <template slot-scope="scope">
                                        <el-popover trigger="hover" placement="top">
                                            {{scope.row.user_name || '-'}}
                                            <div slot="reference" class="wlm-table-wrapper" style="width:100px;">
                                                {{scope.row.user_name || '-'}}
                                            </div>
                                        </el-popover>
                                    </template>
                                </el-table-column>
                                <el-table-column label="用户名">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.real_name!='' && scope.row.real_name  || '-'}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column label="注册时间">
                                    <template slot-scope="scope">
                                        <span>{{scope.row.create_time }}</span>
                                    </template>
                                </el-table-column>
                            </template>
                        </template>
                        <template v-if="isDistributor">
                            <el-table-column label="姓名">
                                <template slot-scope="scope">
                                    <span>{{scope.row.real_name}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="分销等级">
                                <template slot-scope="scope">
                                    <span>{{scope.row.leave_title||'-'}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="手机号">
                                <template slot-scope="scope">
                                    <span>{{scope.row.mobile||'-'}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="注册时间">
                                <template slot-scope="scope">
                                    <span>{{ scope.row.create_time }}</span>
                                </template>
                            </el-table-column>
                        </template>
                        <slot name="el-table-column"></slot>
                    </el-table>
                </div>
            </div>
        </el-scrollbar>
        <div class="pagination-content flex-row flex-justify-b flex-align-c">
            <el-row class="pagination-btns">
                <!-- <el-checkbox class="check-all" :disabled="!hasTableData" true-label="1" false-label="0" v-model="tableFormatData.userTable.files.checkall" @change="toggleSelection">全部</el-checkbox>
                    <el-button class="right-8" :disabled="isGroup" size="mini" @click="delTableList">删除</el-button> -->
            </el-row>
            <el-pagination style="margin-top:20px;margin-bottom:20px;margin-right: 25px;" :disabled="!hasTableData" @size-change="listPageChange" @current-change="changeUserSizePage" :current-page.sync="tableFormatData.userTable.pagination.page" :page-sizes="tableFormatData.userTable.pagination.pagesizes" :page-size.sync="tableFormatData.userTable.pagination.list_rows" layout="total, sizes, prev, pager, next, jumper" :total="hasTableData?tableFormatData.userTable.pagination.total : 0">
            </el-pagination>
        </div>
        <div class="wlm-dialog-fixfooter">
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogTableVisible = false;output(saveList)">确 定</el-button>
            </span>
        </div>
    </el-dialog>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  userList,
  memberIndex
} from '@/api/user'
import defaultConfig from './utils/config'
import mixins from '@/mixins/mixins'
export default {
  mixins: [defaultConfig.mixins, mixins.getters('Table')],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    }
  },
  watch: {
    'config.initList': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          // console.log(newData)
          this.saveList = newData
        }
      },
      immediate: true,
      deep: false
    },
    'config.requestApi': {
      handler(newData, oldData) {
        if (newData) {
          this.tableFormatData.userTable.api.getList = newData
          this.tableType = 'distributor'
        }
      },
      immediate: true,
      deep: false
    }
  },
  computed: {
    isUser() {
      return this.tableType === 'user'
    },
    isDistributor() {
      return this.tableType === 'distributor'
    },
    ...mapGetters([
      'version'
    ]),
    getVersion() {
      return this.$store.getters.version
    },
    isAdmin() {
      return this.getVersion === 'admin'
    }
  },
  data() {
    return {
      tableType: 'user',
      sourceType: {
        '1': '导入',
        '2': '微信小程序',
        '3': 'H5',
        '4': '公众号',
        '5': '安卓',
        '6': '苹果',
        '7': '支付宝小程序',
        '8': '百度小程序',
        '9': '头条小程序',
        '-': '-'
      },
      localId: '',
      currentRow: [],
      saveList: [],
      closable: true,
      disabled: false,
      dialogTableVisible: false,
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList: userList
          },
          tableData: [],
          files: {
            keyword: '',
            real_name: '',
            ids: [],
            checkall: '0'
          },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0
          }
        }
      }
    }
  },
  created() {
    console.log(this.$store)
    this.tableFormatData.userTable.api.getList = this.isAdmin ? memberIndex : userList
    // this.$nextTick(() => {
    //   console.log(this.config.saveList)
    // })
  },
  destoryed() {
    this.saveList = []
    this.currentRow = []
  },
  components: {

  },
  methods: {
    clearData() {
      this.saveList = []
    },
    toggle() {
      this.dialogTableVisible = !this.dialogTableVisible
    },
    changeUserSizePage(page) {
      if (!this.config.isNotUnique) {
        this.currentRow = []
        this.tableFormatData.userTable.tableData = []
      }
      this.tableFormatData.userTable.pagination.page = page
      this.getTableList({ bindKey: 'ChooseUser' })
    },
    changeTableCallBack({ event, params: { argument = {}, response }}) {
      if (event === 'getList' && argument.bindKey === 'ChooseUser') {
        const { data: { data: { current_page = 1 }}} = response
        this.tableFormatData.userTable.pagination.page = current_page
      }
    },
    handleSelectionChange(saveItem) {
      if (this.config.isNotUnique) {
        saveItem.map(item => {
          const hasItem = this.currentRow.findIndex(newItem => {
            return newItem.user_id === item.user_id
          })

          if (hasItem === -1) {
            const { user_id, nickName } = item
            this.currentRow.push({ user_id, nickName })
          }
        })
      } else {
        if (saveItem) {
          if (saveItem.row.checked) {
            if (this.currentRow.length > 0 && saveItem.row.user_id !== this.localId) {
              this.currentRow[0]['row']['checked'] = false
            }
            this.currentRow = [saveItem]
            this.saveList = [saveItem.row]
            this.localId = saveItem.row.user_id
          } else {
            console.log('xf')
            this.saveList = []
          }
        }
      }
    },
    handleClose(tag, index) {
      console.log(tag, 'tag')
      console.log(index, 'index')
      if (this.config.isNotUnique) {
        const newIndex = this.tableFormatData.userTable.tableData.findIndex(item => {
          return tag.user_id === item.user_id
        })
        // console.log(this.tableFormatData.userTable.tableData[index].user_id)
        this.$refs[`${this.$currentTable}`].toggleRowSelection(this.tableFormatData.userTable.tableData[newIndex])
      }

      console.log(this.saveList, 'handleClose')
      this.saveList.some((item, index) => {
        const isId = item.user_id === tag.user_id
        if (isId) {
          item.checked = false
          this.saveList.splice(index, 1)
          return isId
        }
      })
      console.log(this.saveList, 'handleClose')
      this.output(this.saveList)
    },
    // toggleSelection() {
    //   // col checkbox 选择切换
    //   if (this['userTable']) {
    //     this['userTable'].forEach(
    //       row => {
    //         this.$refs['userTable'].toggleRowSelection(row)
    //       }
    //     )
    //   } else {
    //     this.clearSelection()
    //   }
    // },
    output(saveList) {
      if (Object.prototype.toString.call(this.changeEvt) === '[object Function]') {
        if (this.config.isNotUnique) {
          this.saveList = this.currentRow
          saveList = this.currentRow
          this.currentRow = []
        }
        this.changeEvt(saveList)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-userlist {
    margin-bottom: 10px;

    /deep/ .pagination-content .el-input {
        width: 100px;
    }

    .tag-list .el-tag {
        width: auto;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-bottom: 5px;

        &+.el-tag {
            margin-left: 5px;
        }
    }
}
</style>
